<?php

namespace common\components\api_tool;

use Carbon\Carbon;
use common\components\wtools\tools\ArrayHelper;
use GuzzleHttp\Client;

class H5Api extends ApiTool
{
    public $apiUri = '/h5Api';
    public $token;
    public $key;

    public $proxy = [];

    public function configure($conf)
    {
        $this->baseUri = $conf['baseUri'];
        $this->apiUri = $conf['apiUri'];
        $this->token = $conf['token'];
        $this->key = $conf['key'];
        $this->proxy = $conf['proxy'];
    }

    public function guestPost($uri, $form_params = []) {
        $conf = ['base_uri' => $this->getFullUrl($uri), 'verify' => YII_ENV_PROD];
        if ($this->proxy) {
            $conf['proxy'] = $this->proxy;
        }
        $client = new Client($conf);
        $resp = $client->request("POST", "", [
            'form_params' => $form_params,
        ]);
        $resp_content = $resp->getBody()->getContents();
        $resp_arr = json_decode($resp_content, true);
        if (!YII_ENV_PROD) {
            if (!isset($resp_arr['code']) || $resp_arr['code'] != 200) {
                throw new \Exception($resp_content);
            }
        }
        return $resp_arr;
    }

    /**
     * @param $uri
     * @param $form_params
     * @return mixed
     * @throws
     */
    public function post($uri, $form_params = [])
    {
        $form_params = $this->generateFormParams($form_params);
        return $this->guestPost($uri, $form_params);
    }

    /**
     * @param $user
     * @param array $form_params
     * @return array
     */
    public function generateFormParams($form_params = [])
    {
        $form_params['token'] = $this->token;
        $form_params['timestamp'] = Carbon::now()->timestamp;
        $form_params['nonce'] = $form_params['timestamp'].rand(10000000, 40000000);
        $p = $form_params;
        $p['key'] = $this->key;
        ksort($p);
        unset($p['sign']);
        $p_arr = [];
        foreach ($p as $k => $v) {
            $p_arr[] = $k."=".$v;
        }
        $p_str = ArrayHelper::arr2str($p_arr, '&');
        $form_params['sign'] = md5($p_str);
        return $form_params;
    }

    /**
     * @param $uri
     * @return string
     */
    public function getFullUrl($uri = "")
    {
        return $this->baseUri.$this->apiUri.$uri;
    }
}